package cn.virens.web.components.shiro.simple.ajax;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.apache.shiro.web.servlet.AdviceFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.cors.CorsUtils;

public class AjaxLogoutFilter extends AdviceFilter {
	private Logger logger = LoggerFactory.getLogger(LogoutFilter.class);

	protected Subject getSubject(ServletRequest request, ServletResponse response) {
		return SecurityUtils.getSubject();
	}

	@Override
	protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
		return CorsUtils.isPreFlightRequest((HttpServletRequest) request) || onPreHandle(request, response);
	}

	protected boolean onPreHandle(ServletRequest request, ServletResponse response) throws Exception {
		try {
			getSubject(request, response).logout();
		} catch (SessionException ise) {
			logger.debug("Encountered session exception during logout.  This can generally safely be ignored.", ise);
		}

		return AjaxUtil.write(request, response, AjaxUtil.success("Logout", "退出成功"));
	}
}
